package com.fdb.efp.riskm.api.rest;

import java.util.*;

import com.alibaba.druid.sql.dialect.oracle.parser.OracleUpdateParser;
import com.alibaba.fastjson.JSONObject;
import com.fdb.efp.riskm.api.service.RscWarnLoanProcessService;
import com.fdb.basic.framework.core.constant.ApplicationConstance;
import com.fdb.basic.framework.core.exception.ESBException;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.cdp.pboc.service.facade.CreditQueryDetailService;
import com.fdb.cdp.pboc.service.vo.CreditQueryDetailVO;
import com.fdb.cdp.pboc.service.vo.ZXHtmlInfoVO;
import com.fdb.efp.console.service.facade.SDicService;
import com.fdb.efp.console.service.vo.SDicListVO;
import com.fdb.efp.console.service.vo.SDicVO;
import com.fdb.efp.esb.service.bo.req.basicfn.QueryRscWarnLoanReqBean;
import com.fdb.efp.esb.service.bo.req.basicfn.RscWarnLoanDatasReqBean;
import com.fdb.efp.esb.service.bo.resp.basicfn.QueryRscWarnLoanRespBean;
import com.fdb.efp.esb.service.bo.resp.basicfn.RscWarnLoanDatasRespBean;
import com.fdb.efp.esb.service.facade.basicfn.RscWarnLoanDatasService;
import com.fdb.efp.riskm.service.facade.RscWarnGnlHistRuleInfoService;
import com.fdb.efp.riskm.service.vo.LmtTerminateAppVO;
import com.fdb.efp.riskm.service.vo.PspSpecCheckCusVO;
import com.fdb.efp.riskm.service.vo.RscWarnGnlHistRuleInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fdb.basic.framework.core.constant.DataRuleType;
import com.fdb.basic.framework.core.constant.PubConstant;
import com.fdb.basic.framework.core.constant.ResponseData;
import com.fdb.basic.framework.web.controller.AbstractController;
import com.fdb.efp.ctr.service.facade.CtrLoanContService;
import com.fdb.efp.e4a.service.facade.SRoleDataRuleService;
import com.fdb.efp.riskm.service.facade.RscWarnLoanService;
import com.fdb.efp.riskm.service.vo.RscWarnLoanVO;


@RestController
@RequestMapping("/api")
public class RscWarnLoanController extends AbstractController  {
	
	@Autowired
	@Qualifier("rscWarnLoanService")
	private RscWarnLoanService rscWarnLoanService;
	@Autowired
	@Qualifier("ctrLoanContService")
	private CtrLoanContService ctrLoanContService;
	@Autowired
	@Qualifier("sRoleDataRuleService")
	private SRoleDataRuleService sRoleDataRuleService;
	@Autowired
	@Qualifier("rscWarnGnlHistRuleInfoService")
	private RscWarnGnlHistRuleInfoService rscWarnGnlHistRuleInfoService;

	@Autowired
	private RscWarnLoanProcessService rscWarnLoanProcessService;

	@Autowired
	private SDicService sDicService;

	/**
	 * 列表数据查询
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value="/rsc/warn/loans", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<RscWarnLoanVO>> queryRscWarnLoanAll(
			@RequestBody RscWarnLoanVO vo) {	
		List<RscWarnLoanVO> outputVo = null;
		Map<String,String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(), getUserRoles());
		vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PRD_CODE));
		DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
		setUserInfoToVO(vo);
		if (!StringUtil.isNullorBank(vo.getExportFlag()) && "exp".equals(vo.getExportFlag())) {
			// 根据权限方案调用不同的方案进行数据查询
			switch (dataRuleType) {
				case Owner:
					outputVo = rscWarnLoanService.queryExAllOwner(vo);
					break;
				case CurrOrg:
					outputVo = rscWarnLoanService.queryExAllCurrOrg(vo);
					break;
				case CurrDownOrg:
					outputVo = rscWarnLoanService.queryExAllCurrDownOrg(vo);
					break;
				//		case CurrOwnerPrd:
				//			outputVo = rscWarnLoanService.queryAllCurrOwnerPrd(vo);
				//			break;
				default:
					outputVo = rscWarnLoanService.queryExAllOwner(vo);
					break;
			}
		} else if (StringUtil.isNullorBank(vo.getExportFlag())){
			// 根据权限方案调用不同的方案进行数据查询
			switch (dataRuleType) {
				case Owner:
					outputVo = rscWarnLoanService.queryAllOwner(vo);
					break;
				case CurrOrg:
					outputVo = rscWarnLoanService.queryAllCurrOrg(vo);
					break;
				case CurrDownOrg:
					outputVo = rscWarnLoanService.queryAllCurrDownOrg(vo);
					break;
		//		case CurrOwnerPrd:
		//			outputVo = rscWarnLoanService.queryAllCurrOwnerPrd(vo);
		//			break;
				default:
					outputVo = rscWarnLoanService.queryAllOwner(vo);
					break;
			}
		}

		return getResponseData(outputVo);
		
	}
	
	/**
	 * 根据主键查询详情
	 * @return
	 */
	@RequestMapping(value="/rsc/warn/loan/{taskNo}", method=RequestMethod.GET)
	public @ResponseBody ResponseData<RscWarnLoanVO> queryByPk(@PathVariable("taskNo") String taskNo) {		
		RscWarnLoanVO inVo = new RscWarnLoanVO();
				inVo.setTaskNo(taskNo);
		RscWarnLoanVO outputVo = rscWarnLoanService.queryByPk(inVo);
		return getResponseData(outputVo);
		
	}
	
	/**
	 * 根据主键删除信息
	 * @param rscWarnLoan
	 * @return
	 */
	@RequestMapping(value="/rsc/warn/loan", method=RequestMethod.DELETE)
	public @ResponseBody ResponseData<Integer> deleteByPk(@RequestBody RscWarnLoanVO inRscWarnLoanVo) {		
		int outputVo = rscWarnLoanService.deleteByPk(inRscWarnLoanVo);
		return getResponseData(outputVo);
		
	}
	
	/**
	 * 根据主键更新信息
	 * @param inRscWarnLoanVo
	 * @return
	 */
	@RequestMapping(value="/rsc/warn/loan", method=RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody RscWarnLoanVO inRscWarnLoanVo) {		
		int outputVo = rscWarnLoanService.updateByPk(inRscWarnLoanVo);
		return getResponseData(outputVo);
		
	}
	
	/**
	 * 新增数据
	 * @param inRscWarnLoanVo
	 * @return
	 */
	@RequestMapping(value="/rsc/warn/loan", method=RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertRscWarnLoan(@RequestBody RscWarnLoanVO inRscWarnLoanVo) {
		int outputVo = rscWarnLoanService.insertRscWarnLoan(inRscWarnLoanVo);
		return getResponseData(outputVo);
		
	}
	
	/**
	 * 列表数据导出
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value="/rsc/warn/loans/export", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<RscWarnLoanVO>> queryRscWarnLoanOut(
			@RequestBody RscWarnLoanVO inRscWarnLoanVo) {		
		List<RscWarnLoanVO> outputVo = rscWarnLoanService.queryRscWarnLoanOut(inRscWarnLoanVo);
		return getResponseData(outputVo);
		
	}
	/**
	 * 根据授信协议编号查询风险预警台账
	 * @return
	 */
	@RequestMapping(value="/rsc/warn/loans/lmt/cont/no", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<RscWarnLoanVO>> queryRscWarnLoansByLmtContNo(
			@RequestBody Map<String, String> data,@RequestBody RscWarnLoanVO inRscWarnLoanVo ) {
		String lmtContNo = data.get("lmtContNo");
		List<String> contNos = ctrLoanContService.queryContNoByLmtContNo(lmtContNo);
		List<RscWarnLoanVO> outputVo = rscWarnLoanService.queryRscWarnLoanByContNos(inRscWarnLoanVo,contNos);
		return getResponseData(outputVo);
	}
	/**/
	@RequestMapping(value="/rec/rsc/warnInfo", method=RequestMethod.POST)
	public @ResponseBody ResponseData<List<RscWarnLoanVO>> queryWarnInfoDetails(@RequestBody RscWarnLoanVO inRscWarnLoanVo) {
		List<RscWarnLoanVO> outputVo = rscWarnLoanService.queryByCondByPage(inRscWarnLoanVo);
		if (outputVo != null && outputVo.size() > 0) {
			//查询字典值做映射处理
			SDicListVO sDicListVO = new SDicListVO();
			sDicListVO.setOpttype("RULE_CODE_NAME_TOW_LEVEL");
			List<SDicListVO> sDicListVOS = sDicService.queryByopttype(sDicListVO);
			if (sDicListVOS != null && sDicListVOS.size() > 0) {
				List<SDicVO> sDicVOS = sDicListVOS.get(0).getsDicVOs();
				if (sDicVOS != null) {
					for (RscWarnLoanVO rscWarnLoanVO : outputVo) {
						if (!"02".equals(rscWarnLoanVO.getRiskLevel())) {
							rscWarnLoanVO.setRuleName("");
							continue;
						}
						SDicVO sDicVO = sDicVOS.stream().filter(s -> rscWarnLoanVO.getRuleCode().equals(s.getEnname())).findFirst().orElse(null);
						if (!Objects.isNull(sDicVO)) {
							rscWarnLoanVO.setRuleName(sDicVO.getCnname());
						}
					}
				}
			}
		}
		return getResponseData(outputVo);
	}

	@RequestMapping(value="/rec/hist/rsc/warn", method=RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> queryHistRecRscWarnLoans(
			@RequestBody RscWarnLoanVO inRscWarnLoanVo) throws Exception {
		int outputVo = 0;
		try {
			//清空历史临时数据
			int delFlag = rscWarnGnlHistRuleInfoService.updateRuleValue();
			//调用通用决策历史数据单个实时查询接口获取外部历史数据
			RscWarnLoanDatasRespBean rs = rscWarnLoanProcessService.getHistRscWarnLoanDatas(inRscWarnLoanVo);
			logger.info("调用通用决策历史数据单个实时查询接口获取到的外部历史数据为：" + JSONObject.toJSONString(rs));
			if (Objects.isNull(rs)) throw new Exception("调用通用决策历史数据单个实时查询接口获取到的外部历史数据结果为空！");
			//处理风险预警外部数据
			outputVo = rscWarnLoanProcessService.dealWithRscWarnGnlVal(inRscWarnLoanVo.getCusId(),rs);
			if (outputVo < 0) throw new Exception("调用通用决策历史数据单个实时查询接口获取到的外部历史数据后，更新数据信息失败！");
		} catch (Exception e) {
			logger.error("处理错误：" + e.getMessage());
			return ResponseData.create(null,ApplicationConstance.FAILURE,e.getMessage(),false);
		}
		return getResponseData(outputVo);
	}

	@RequestMapping(value = "/rsc/warn/loan/hist/rule", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<RscWarnGnlHistRuleInfoVO>> queryRiskRuleHistAndCurrVal(@RequestBody RscWarnGnlHistRuleInfoVO rscWarnGnlHistRuleInfoVO) {
		List<RscWarnGnlHistRuleInfoVO> outputVo = rscWarnGnlHistRuleInfoService.queryRiskRuleHistAndCurrVal(rscWarnGnlHistRuleInfoVO);
		return getResponseData(outputVo);
	}

	@RequestMapping(value="/rec/curr/rsc/warn", method=RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> queryCurrRecRscWarnLoans(
			@RequestBody RscWarnLoanVO inRscWarnLoanVo) throws Exception {
		int outputVo = 0;
		String errMsg ="";
		try {
			//查询要查看的风险信息
			RscWarnLoanVO queryOldRs = rscWarnLoanService.queryByCond(inRscWarnLoanVo);
			if (Objects.isNull(queryOldRs)) {
				throw new Exception("未查询到历史数据！");
			}
			//调用通用决策历史数据单个实时查询接口获取实时数据，并判断信息是否一致
			boolean flag = rscWarnLoanProcessService.getCurrRscWarnLoanDatas(inRscWarnLoanVo);
			//查询更新后的风险预警数据
			if (flag) {
				outputVo = 1;
			} else {
				throw new Exception("返回数据请求id和发起请求的请求id不一致！");
			}
		} catch (Exception e) {
			logger.error("处理错误：" + e.getMessage());
			return ResponseData.create(null,ApplicationConstance.FAILURE,e.getMessage(),false);
		}
		return getResponseData(outputVo);
	}

	@RequestMapping(value = "/getrec/curr/rsc/warn", method = RequestMethod.POST)
	public @ResponseBody
	ResponseData<List<RscWarnLoanVO>> getCurrRecRscWarnLoans(
			@RequestBody RscWarnLoanVO inRscWarnLoanVo) throws Exception {
		List<RscWarnLoanVO> outputVo = null;
		try {
			//查询要查看的风险信息
			RscWarnLoanVO queryOldRs = rscWarnLoanService.queryByCond(inRscWarnLoanVo);
			outputVo = rscWarnLoanProcessService.queryRecRscWarnLoan(inRscWarnLoanVo, queryOldRs);
			if (Objects.isNull(outputVo)) throw new Exception("未查询到修改后的数据！");
		} catch (Exception e) {
			logger.error("处理错误：" + e.getMessage());
			return ResponseData.create(null, ApplicationConstance.FAILURE, e.getMessage(), false);
		}
		return getResponseData(outputVo);
	}

	@RequestMapping(value = "/get/zxrpt/show", method = RequestMethod.POST)
	public @ResponseBody ResponseData<ZXHtmlInfoVO> getZXHtmlInfo(@RequestBody RscWarnLoanVO inRscWarnLoanVo) throws Exception {
		ZXHtmlInfoVO outputVo = new ZXHtmlInfoVO();
		try {
			outputVo = rscWarnLoanProcessService.getZXHtmlReport(inRscWarnLoanVo);
		} catch (Exception e) {
			logger.error("处理错误：" + e.getMessage());
			return ResponseData.create(null,ApplicationConstance.FAILURE,e.getMessage(),false);
		}
		return getResponseData(outputVo);
	}

	@RequestMapping(value = "/get/histzxrpt/show", method = RequestMethod.POST)
	public @ResponseBody ResponseData<ZXHtmlInfoVO> getHistZXHtmlInfo(@RequestBody RscWarnLoanVO inRscWarnLoanVo) throws Exception {
		ZXHtmlInfoVO outputVo = new ZXHtmlInfoVO();
		try {
			outputVo = rscWarnLoanProcessService.getHistZXHtmlReport(inRscWarnLoanVo);
		} catch (Exception e) {
			logger.error("处理错误：" + e.getMessage());
			return ResponseData.create(null,ApplicationConstance.FAILURE,e.getMessage(),false);
		}
		return getResponseData(outputVo);
	}

	@RequestMapping(value = "/rsc/warn/zxReport", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<ZXHtmlInfoVO>> getZXHtmlInfos(@RequestBody RscWarnLoanVO inRscWarnLoanVo) {
		List<ZXHtmlInfoVO> outputVo = null;
		try {
			outputVo = rscWarnLoanProcessService.getZXHtmlReportsByCus(inRscWarnLoanVo);
		} catch (Exception e) {
			logger.error("处理错误：" + e.getMessage());
			return ResponseData.create(null,ApplicationConstance.FAILURE,e.getMessage(),false);
		}
		return getResponseData(outputVo);
	}
	@RequestMapping(value = "/rsc/warn/byCertCode", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<RscWarnLoanVO>> queryByCertCode(@RequestBody LmtTerminateAppVO lmtTerminateAppVO) {
		List<RscWarnLoanVO> outputVo = new ArrayList<>();
		try {
			List<RscWarnLoanVO> querys = rscWarnLoanService.queryByCertCode(lmtTerminateAppVO.getCertCode(), lmtTerminateAppVO.getCertType());
			//去重
			for (RscWarnLoanVO query : querys) {
				boolean has = false;
				for (RscWarnLoanVO rscWarnLoanVO : outputVo) {
					if (query.getRuleCode().equals(rscWarnLoanVO.getRuleCode())) {
						has = true;
						break;
					}
				}
				if (!has) {
					outputVo.add(query);
				}
			}
		} catch (Exception e) {
			logger.error("处理错误：" + e.getMessage());
			return ResponseData.create(null,ApplicationConstance.FAILURE,e.getMessage(),false);
		}
		return getResponseData(outputVo);
	}
}
